package com.example.administrator.myapplication.contact;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.administrator.myapplication.MobileBook;
import com.example.administrator.myapplication.R;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2018/11/2.
 */

public class PhoneTest2 extends Activity {

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                threadInfo();
                queryContacts();
            }
        });
        checkPermissions();
//        handlemobilebookSucess();


    }
    private void checkPermissions() {
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(PhoneTest2.this,
                Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_CONTACTS);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(PhoneTest2.this, permissions, 1);
        } else {


        }

    }
    private void queryContacts() {
        List<MobileBook.MobilebookBean> listbean = new ArrayList<>() ;
        MobileBook mobileBook = new MobileBook();

        // 获取用来操作数据的类的对象，对联系人的基本操作都是使用这个对象
        ContentResolver cr = getContentResolver();
        // 查询contacts表的所有记录
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
        // 如果记录不为空
        if (cursor.getCount() > 0) {
            // 游标初始指向查询结果的第一条记录的上方，执行moveToNext函数会判断
            // 下一条记录是否存在，如果存在，指向下一条记录。否则，返回false。
            while (cursor.moveToNext()) {
                String rawContactId = "";
                // 从Contacts表当中取得ContactId
                String id = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                Log.v("contactID", id);

                // 获取RawContacts表的游标
                Cursor rawContactCur = cr.query(ContactsContract.RawContacts.CONTENT_URI, null,
                        ContactsContract.RawContacts._ID + "=?", new String[] { id }, null);

                MobileBook.MobilebookBean mobilebookBean = new MobileBook.MobilebookBean();
                // 该查询结果一般只返回一条记录，所以我们直接让游标指向第一条记录
                if (rawContactCur.moveToFirst()) {
                    // 读取第一条记录的RawContacts._ID列的值
                    rawContactId = rawContactCur.getString(rawContactCur
                            .getColumnIndex(ContactsContract.RawContacts._ID));
                    Log.v("rawContactID", rawContactId);

                }
                // 关闭游标
                rawContactCur.close();
                // 读取号码
                if (Integer
                        .parseInt(cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // 根据查询RAW_CONTACT_ID查询该联系人的号码
                    Cursor phoneCur = cr
                            .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID
                                            + "=?",
                                    new String[] { rawContactId }, null);
                    // 上面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                    // 可以用下面的phoneUri代替
                    // Uri
                    // phoneUri=Uri.parse("content://com.android.contacts/data/phones");

                    // 一个联系人可能有多个号码，需要遍历
                    while (phoneCur.moveToNext()) {
                        // 获取号码
                        String number = phoneCur
                                .getString(phoneCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.v("number", number);
                        // 获取号码类型
                        String type = phoneCur
                                .getString(phoneCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                        Log.v("type", type);

                        // 获取号码类型
                        String name = phoneCur
                                .getString(phoneCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        mobilebookBean.setName(name);
                        mobilebookBean.setPhone(number);
                        Log.v("=====ccc", name + "====" +number);

                    }
                    listbean.add(mobilebookBean);
//                    if (!TextUtils.isEmpty(mobilebookBean.getName())&&!TextUtils.isEmpty(mobilebookBean.getPhone())) {
//                        listbean.add(mobilebookBean);
//                        Log.v("=====cccddd",listbean.size()+"==="+mobilebookBean.getName() + "====" +mobilebookBean.getPhone());
//                    }
//                    Log.v("=====cccddd",listbean.size()+"");

//                listbean.add(mobilebookBean);
                    mobileBook.setMobilebook(listbean);

                    String mobilsJson = new Gson().toJson(mobileBook).toString();
                    Log.v("=====mobilsJsond",mobilsJson);
                    tv.setText(listbean.size()+"==aaa=="+mobilsJson);
                    phoneCur.close();

                }
            }


            cursor.close();
        }

    }

}
